<template>
  <view class="customer-list-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">客户管理</block>
      <block slot="right">
        <view class="flex align-center">
          <text class="cuIcon-add text-white margin-right-sm" @click="addCustomer"></text>
          <text class="cuIcon-search text-white" @click="showSearch = true"></text>
        </view>
      </block>
    </cu-custom>

    <!-- 搜索栏 -->
    <view v-if="showSearch" class="search-bar padding bg-white">
      <view class="search-input-wrapper">
        <input 
          v-model="searchKeyword" 
          class="search-input" 
          placeholder="搜索客户名称、联系人..."
          @input="handleSearch"
        />
        <text class="cuIcon-search search-icon"></text>
      </view>
    </view>

    <!-- 筛选条件 -->
    <view class="filter-bar bg-white padding-sm">
      <scroll-view scroll-x class="filter-scroll">
        <view class="filter-tags">
          <view 
            v-for="filter in filterOptions" 
            :key="filter.key"
            class="filter-tag" 
            :class="{ 'active': activeFilter === filter.key }"
            @click="setFilter(filter.key)"
          >
            {{ filter.label }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 客户列表 -->
    <view class="customer-list">
      <view 
        v-for="customer in filteredCustomers" 
        :key="customer.id"
        class="customer-item bg-white margin-bottom-sm"
        @click="viewCustomer(customer)"
      >
        <view class="customer-header padding flex align-center justify-between">
          <view class="customer-info">
            <view class="customer-name text-lg text-bold">{{ customer.name }}</view>
            <view class="customer-type text-sm text-gray margin-top-xs">
              {{ getCustomerTypeText(customer.type) }} · {{ customer.industry }}
            </view>
          </view>
          <view class="customer-status" :class="[getStatusClass(customer.status)]">
            {{ getStatusText(customer.status) }}
          </view>
        </view>
        
        <view class="customer-details padding-top-sm padding-lr">
          <view class="detail-row flex align-center margin-bottom-xs">
            <text class="cuIcon-phone detail-icon"></text>
            <text class="detail-text">{{ customer.phone || '暂无电话' }}</text>
          </view>
          <view class="detail-row flex align-center margin-bottom-xs">
            <text class="cuIcon-location detail-icon"></text>
            <text class="detail-text">{{ customer.address || '暂无地址' }}</text>
          </view>
          <view class="detail-row flex align-center">
            <text class="cuIcon-people detail-icon"></text>
            <text class="detail-text">联系人：{{ customer.contactName || '暂无' }}</text>
          </view>
        </view>

        <view class="customer-footer padding flex align-center justify-between">
          <view class="customer-stats">
            <text class="stat-item">订单：{{ customer.orderCount || 0 }}</text>
            <text class="stat-item margin-left">项目：{{ customer.projectCount || 0 }}</text>
          </view>
          <view class="customer-actions">
            <text class="cuIcon-phone action-btn text-blue" @click.stop="callCustomer(customer)"></text>
            <text class="cuIcon-edit action-btn text-orange margin-left" @click.stop="editCustomer(customer)"></text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more padding text-center">
      <button class="cu-btn line-blue sm" @click="loadMore" :loading="loading">
        {{ loading ? '加载中...' : '加载更多' }}
      </button>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredCustomers.length === 0 && !loading" class="empty-state text-center padding-xl">
      <image src="/static/images/empty-customer.png" class="empty-image"></image>
      <view class="empty-text text-gray margin-top">暂无客户数据</view>
      <button class="cu-btn bg-blue margin-top" @click="addCustomer">添加客户</button>
    </view>

    <!-- 悬浮添加按钮 -->
    <view class="fab" @click="addCustomer">
      <text class="cuIcon-add text-white"></text>
    </view>
  </view>
</template>

<script>
import authService from '../../../src/services/auth.js'

export default {
  data() {
    return {
      showSearch: false,
      searchKeyword: '',
      activeFilter: 'all',
      loading: false,
      hasMore: true,
      customers: [],
      filterOptions: [
        { key: 'all', label: '全部' },
        { key: 'potential', label: '潜在客户' },
        { key: 'active', label: '活跃客户' },
        { key: 'inactive', label: '非活跃' }
      ]
    }
  },

  computed: {
    filteredCustomers() {
      let result = this.customers

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        result = result.filter(customer => 
          customer.name.toLowerCase().includes(keyword) ||
          (customer.contactName && customer.contactName.toLowerCase().includes(keyword))
        )
      }

      // 状态过滤
      if (this.activeFilter !== 'all') {
        result = result.filter(customer => customer.status === this.activeFilter)
      }

      return result
    }
  },

  onLoad() {
    this.checkPermission()
    this.loadCustomers()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },

  methods: {
    checkPermission() {
      if (!authService.hasPermission('crm:customer:view')) {
        uni.showToast({
          title: '无权限访问',
          icon: 'none'
        })
        uni.navigateBack()
        return
      }
    },

    async loadCustomers() {
      this.loading = true
      try {
        // 模拟API调用
        await this.simulateApiCall()
        this.customers = this.getMockCustomers()
      } catch (error) {
        console.error('加载客户失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },

    getMockCustomers() {
      return [
        {
          id: '1',
          name: '张三门窗厂',
          type: 'enterprise',
          industry: '建材制造',
          status: 'active',
          phone: '138****1234',
          address: '广东省深圳市南山区',
          contactName: '张总',
          orderCount: 5,
          projectCount: 3
        },
        {
          id: '2',
          name: '李四装饰公司',
          type: 'enterprise',
          industry: '装饰装修',
          status: 'potential',
          phone: '139****5678',
          address: '广东省广州市天河区',
          contactName: '李经理',
          orderCount: 2,
          projectCount: 1
        },
        {
          id: '3',
          name: '王五建筑工程',
          type: 'enterprise',
          industry: '建筑工程',
          status: 'inactive',
          phone: '137****9012',
          address: '广东省东莞市',
          contactName: '王工',
          orderCount: 0,
          projectCount: 0
        }
      ]
    },

    simulateApiCall() {
      return new Promise(resolve => {
        setTimeout(resolve, 1000)
      })
    },

    handleSearch() {
      // 搜索逻辑已在computed中处理
    },

    setFilter(filterKey) {
      this.activeFilter = filterKey
    },

    getCustomerTypeText(type) {
      const typeMap = {
        'enterprise': '企业客户',
        'individual': '个人客户'
      }
      return typeMap[type] || '未知类型'
    },

    getStatusClass(status) {
      const classMap = {
        'active': 'status-active',
        'potential': 'status-potential',
        'inactive': 'status-inactive'
      }
      return classMap[status] || 'status-inactive'
    },

    getStatusText(status) {
      const textMap = {
        'active': '活跃',
        'potential': '潜在',
        'inactive': '非活跃'
      }
      return textMap[status] || '未知'
    },

    viewCustomer(customer) {
      uni.navigateTo({
        url: `/pages/crm/customer/detail?id=${customer.id}`
      })
    },

    addCustomer() {
      if (!authService.hasPermission('crm:customer:create')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: '/pages/crm/customer/add'
      })
    },

    editCustomer(customer) {
      if (!authService.hasPermission('crm:customer:edit')) {
        uni.showToast({
          title: '无权限操作',
          icon: 'none'
        })
        return
      }
      
      uni.navigateTo({
        url: `/pages/crm/customer/edit?id=${customer.id}`
      })
    },

    callCustomer(customer) {
      if (customer.phone) {
        uni.makePhoneCall({
          phoneNumber: customer.phone.replace(/\*/g, '')
        })
      } else {
        uni.showToast({
          title: '暂无电话号码',
          icon: 'none'
        })
      }
    },

    async refreshData() {
      this.customers = []
      await this.loadCustomers()
    },

    async loadMore() {
      if (this.loading) return
      
      this.loading = true
      try {
        await this.simulateApiCall()
        // 模拟没有更多数据
        this.hasMore = false
      } catch (error) {
        console.error('加载更多失败:', error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.customer-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.search-bar {
  .search-input-wrapper {
    position: relative;
    
    .search-input {
      width: 100%;
      height: 70rpx;
      padding: 0 60rpx 0 20rpx;
      background-color: #f8f9fa;
      border-radius: 35rpx;
      font-size: 28rpx;
      border: none;
    }
    
    .search-icon {
      position: absolute;
      right: 20rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }
}

.filter-bar {
  .filter-scroll {
    white-space: nowrap;
    
    .filter-tags {
      display: inline-flex;
      
      .filter-tag {
        padding: 12rpx 24rpx;
        margin-right: 16rpx;
        background-color: #f0f0f0;
        border-radius: 20rpx;
        font-size: 26rpx;
        color: #666;
        white-space: nowrap;
        
        &.active {
          background-color: #1890ff;
          color: white;
        }
      }
    }
  }
}

.customer-list {
  padding: 0 24rpx;
  
  .customer-item {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    overflow: hidden;
    
    .customer-header {
      border-bottom: 1rpx solid #f0f0f0;
      
      .customer-status {
        padding: 8rpx 16rpx;
        border-radius: 16rpx;
        font-size: 24rpx;
        
        &.status-active {
          background-color: #f6ffed;
          color: #52c41a;
        }
        
        &.status-potential {
          background-color: #fff7e6;
          color: #fa8c16;
        }
        
        &.status-inactive {
          background-color: #f5f5f5;
          color: #999;
        }
      }
    }
    
    .customer-details {
      .detail-row {
        .detail-icon {
          font-size: 24rpx;
          color: #999;
          width: 32rpx;
        }
        
        .detail-text {
          font-size: 26rpx;
          color: #666;
          margin-left: 12rpx;
        }
      }
    }
    
    .customer-footer {
      border-top: 1rpx solid #f0f0f0;
      
      .customer-stats {
        .stat-item {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .customer-actions {
        .action-btn {
          font-size: 32rpx;
          padding: 8rpx;
        }
      }
    }
  }
}

.load-more {
  margin-bottom: 40rpx;
}

.empty-state {
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    opacity: 0.5;
  }
  
  .empty-text {
    font-size: 28rpx;
    margin-top: 24rpx;
  }
}

.fab {
  position: fixed;
  bottom: 100rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.3);
  z-index: 999;
  
  .cuIcon-add {
    font-size: 40rpx;
  }
}
</style>
